package com.fs.jzzn.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import lombok.extern.log4j.Log4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.fs.base.utils.ApplicationUtils;
import com.fs.base.vo.JsonResponse;
import com.fs.jzzn.pojo.Storage;
import com.fs.jzzn.service.StorageService;

/**
 * @author TiddlerCJ
 */

@Controller
@RequestMapping("/console/storage/rewrite")
@Log4j
public class StorageController {
	@Autowired
	private StorageService storageService;
	
	
	@ResponseBody
	@RequestMapping("newAdd")
	public JsonResponse newAdd(Storage storage) {
		try {
			storageService.saveOrUpdata(storage);
			return JsonResponse.success();
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return JsonResponse.error(e.getMessage());
		}
	}
	
	@ResponseBody
	@RequestMapping("modify")
	public JsonResponse modify(Storage storage, HttpServletRequest request) {
		try {
			Map<String, Object> map = ApplicationUtils.getRequestDatas();
			Storage oldVo = storageService.getStorageRepository().findOne(storage.getId());
			
			String oldJson = JSON.toJSONString(oldVo);
			@SuppressWarnings("unchecked")
			Map<String, Object> oldMap = JSON.parseObject(oldJson, Map.class);
			oldMap.putAll(map);
			
			String json = JSON.toJSONString(oldMap) ;
			
			Storage newVo = JSON.parseObject(json, Storage.class);
			storageService.saveOrUpdata(newVo);
			return JsonResponse.success();
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return JsonResponse.error(e.getMessage());
		}
	}
	
	@ResponseBody
	@RequestMapping("confirm")
	public JsonResponse confirm(String id, HttpServletRequest request) {
		try {
			storageService.confirm(id);
			return JsonResponse.success();
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return JsonResponse.error(e.getMessage());
		}
	}
	
	@GetMapping("delete")
	@ResponseBody
	public JsonResponse delete(String id) {
		try {
			storageService.delete(id);
			return JsonResponse.success();
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return JsonResponse.error(e.getMessage());
		}
	}
}
